#include <iostream>
#include <mysql/mysql.h>
#include <string>
#include <unistd.h>

const std::string host = "127.0.0.1";
const std::string user = "cyq";
const std::string passwd = "12345678";
const std::string db = "test1";
const unsigned int port = 3306;

int main()
{
    // std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;
    MYSQL *my = mysql_init(nullptr);
    if (my == nullptr)
    {
        std::cerr << "init mysql error" << std::endl;
        return 1;
    }

    if (mysql_real_connect(my, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "connect mysql error" << std::endl;
        return 2;
    }
    mysql_set_character_set(my, "utf8");
    // std::string sql = "insert into t2 (id,name) values (2,'李四')";
    std::string sql = "select * from t2";
    int n = mysql_query(my, sql.c_str());
    if (n == 0)
    {
        std::cout << sql << "success: " << n << std::endl;
    }
    else
    {
        std::cout << sql << "error: " << n << std::endl;
        return 3;
    }

    MYSQL_RES *res = mysql_store_result(my);
    if (res == nullptr)
    {
        std::cerr << "mysql_store_result error" << std::endl;
    }

    // 结果有几行
    int rows = mysql_num_rows(res);
    // 结果有几列
    int fields = mysql_num_fields(res);
    std::cout << "行: " << rows << std::endl;
    std::cout << "列: " << fields << std::endl;

    // 属性
    MYSQL_FIELD *fields_array = mysql_fetch_fields(res);
    for (int i = 0; i < fields; i++)
    {
        std::cout << fields_array[i].name << "\t";
    }
    std::cout << "\n";

    // 内容
    for (int i = 0; i < rows; i++)
    {
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < fields; j++)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << "\n";
    }

    // while (true)
    // {
    //     std::cout << "MYSQL>>";
    //     if (!std::getline(std::cin, sql) || sql == "quit")
    //     {
    //         std::cout << "bye bye" << std::endl;
    //         break;
    //     }
    //     int n = mysql_query(my, sql.c_str());
    //     if (n == 0)
    //     {
    //         std::cout << sql << "success: " << n << std::endl;
    //     }
    //     else
    //     {
    //         std::cout << sql << "error: " << n << std::endl;
    //     }
    // }
    // sleep(10);
    // std::cout << "connect mysql success" << std::endl;
    mysql_close(my);
    return 0;
}